#!/usr/bin/with-contenv bashio
# vim: ft=bash
# shellcheck shell=bash
#==============================================================================
# OpenThread BorderRouter Daemon finish script
#==============================================================================
if test "$1" -eq 256 ; then
  e=$((128 + $2))
else
  e="$1"
fi

if test "$e" -ne 0; then
    bashio::log.warning "otbr-agent exited with code $e (by signal $2)."
else
    bashio::log.info "otbr-agent exited with code $e (by signal $2)."
fi

# shellcheck disable=SC1091
. /etc/s6-overlay/scripts/otbr-agent-common

ipset_destroy_if_exist()
{
    # The ipset seems to be in use by the kernel for a brief period,
    # retry destroying it
    while ipset list -n "$1" 2> /dev/null; do
        ipset destroy "$1" || true
    done
}

# shellcheck disable=SC2154,SC2086
while ip6tables -C FORWARD -o $thread_if -j $otbr_forward_ingress_chain 2> /dev/null; do
    # shellcheck disable=SC2086
    ip6tables -D FORWARD -o $thread_if -j $otbr_forward_ingress_chain
done

# shellcheck disable=SC2086
if ip6tables -L $otbr_forward_ingress_chain 2> /dev/null; then
    ip6tables -w -F $otbr_forward_ingress_chain
    ip6tables -w -X $otbr_forward_ingress_chain
fi

ipset_destroy_if_exist otbr-ingress-deny-src
ipset_destroy_if_exist otbr-ingress-deny-src-swap
ipset_destroy_if_exist otbr-ingress-allow-dst
ipset_destroy_if_exist otbr-ingress-allow-dst-swap

# shellcheck disable=SC2154,SC2086
while ip6tables -C FORWARD -i $thread_if -j $otbr_forward_egress_chain 2> /dev/null; do
    ip6tables -D FORWARD -i $thread_if -j $otbr_forward_egress_chain
done

# shellcheck disable=SC2086
if ip6tables -L $otbr_forward_egress_chain 2> /dev/null; then
    ip6tables -w -F $otbr_forward_egress_chain
    ip6tables -w -X $otbr_forward_egress_chain
fi
bashio::log.info "OTBR firewall teardown completed."

if test "$e" -ne 0; then
    echo "$e" > /run/s6-linux-init-container-results/exitcode
    /run/s6/basedir/bin/halt
    # Consider any otbr-agent exit as permanent failure according to s6
    exit 125
fi
